﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace MacNs
{
    /// <summary>
    ///     An encapsulation of the SendARP API call.
    /// </summary>

    public class ArpClient
    {
        [DllImport ("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP (int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

        /// <summary>
        ///     Retrieves the MAC address from an IP address.
        /// </summary>
        /// <param name="IpAddress">
        ///     The textual form of the IP address to resolve.
        /// </param>
        /// <returns>
        ///     The MAC address, in a form that looks like a host
        ///     name, MACxxxxxxxxxxxx so that it has exactly 15 characters.
        /// </returns>

        public static string IpToMacName (string IpAddress)
        {
            System.Net.IPAddress dst = System.Net.IPAddress.Parse (IpAddress);

            byte[] macAddr = new byte[6];
            uint macAddrLen = (uint)macAddr.Length;
            if (SendARP ((int)dst.Address, 0, macAddr, ref macAddrLen) != 0)
                throw new InvalidOperationException ("SendARP failed.");

            string[] str = new string[(int)macAddrLen];
            for (int i = 0; i < macAddrLen; i++)
                str[i] = macAddr[i].ToString ("X2");

            return "MAC" + String.Concat (str);
        }
    }
}
